﻿#include "musicplayer.h"
#include "ui_musicplayer.h"
#include <QDebug>
#include <time.h>
MusicPlayer::MusicPlayer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicPlayer)
    , player(new QMediaPlayer(this)),playlist(new QMediaPlaylist(this))
    , m_http(new QNetworkAccessManager(this)),m_http_Music(new QNetworkAccessManager(this))
    {
    ui->setupUi(this);
setFixedSize(width(),height());
    setUIInit();
    connectInit();  //信号槽初始化
}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}


//UI界面初始化
void MusicPlayer::setUIInit()
{

    //ui->stackedWidget->setCurrentIndex(0);//切换到第一页
    /*-----------------------------------------*/

    /*------------播放器设置播放列表 ------------*/
    player->setPlaylist(playlist);
    player->setVolume(50);         //音量初始值为100
    ui->verticalSlider->setValue(50);


     pModel = new QStandardItemModel(3,3,ui->musicTableView);
     //设置数据模型的表头
     QStringList list = QStringList()<<"歌曲名"<<"专辑"<<"歌手"<<"时长";

     pModel->setHorizontalHeaderLabels(list);//设置数据的表头



     ui->musicTableView->setModel(pModel);


     //创建一个网络访问管理对象
     manager = new QNetworkAccessManager(this);
     connect(manager, SIGNAL(finished(QNetworkReply*)),
             this, SLOT(replyFinished(QNetworkReply*)));

     ui->musicTableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background-color: transparent;};selection-background-color: rgb(77, 77, 77);");


     playlist = new QMediaPlaylist;//媒体播放列表

     player = new QMediaPlayer;//媒体播放器
     player->setPlaylist(playlist);//把播放列表设置给播放器

     //connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
     //connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));
     connect(this,&MusicPlayer::lyricShow,this,&MusicPlayer::lyricTextShow);

    // 绑定播放器的位置变化信号到更新播放进度函数
     connect(player,&QMediaPlayer::positionChanged,this,&MusicPlayer::updateDuration);
}
#include <QMouseEvent>
#include <QMenu>
#include <QDesktopServices>
#include <QFileDialog>
#include <QUrl>
void MusicPlayer::connectInit()
{

    //播放音乐按钮
    connect(ui->playButton,&QPushButton::clicked,[=](){
        /*------------- 判断是否在播放 -------------------*/
        if(player->state() == QMediaPlayer::PlayingState)
        {
            player->pause();    //暂停
            ui->playButton->setIcon(QIcon(":/icon_u090ulefd4/播放.png"));
        }
        else
        {
            player->play();     //播放
            ui->playButton->setIcon(QIcon(":/icon_u090ulefd4/暂停.png"));
        }
    });
    //上一曲按钮 和 下一曲按钮
    connect(ui->upButton,SIGNAL(clicked(bool)),playlist,SLOT(previous()));
    connect(ui->downButton,SIGNAL(clicked(bool)),playlist,SLOT(next()));


    //点击音乐列表播放
    connect(ui->musicTableView,SIGNAL(currentRowChanged(int)),playlist,SLOT(setCurrentIndex(int)));

    //允许用户 拖动滑块调节音量
    connect(ui->verticalSlider,&QSlider::sliderMoved,[=](){

        int count = ui->verticalSlider->value();
        player->setVolume(count);         //音量跟随滑块变化
    });

    //播放本地下载的音乐
    connect(ui->addButton,&QPushButton::clicked,[=](){
        QString filePath = QFileDialog::getOpenFileName(this, tr("Open Music File"), "", tr("Music Files (*.mp3 *.wav *.flac)"));
        player->setMedia(QUrl::fromLocalFile(filePath));
        player->play();
        ui->playButton->setIcon(QIcon(":/icon_u090ulefd4/暂停.png"));
    });
}

void MusicPlayer::on_findpushButton_clicked()
{
    manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(ui->lineEdit_find->text()))));

}

void MusicPlayer::parseJson(QByteArray byteArray)
{
    unsigned int id = -1;
    QString songName;
    QString albumName;
    QString singerName;
    float duration = -1;
    musicIDList.clear();
    playlist->clear();
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())//问文档内部是否是一个对象？
    {
        QJsonObject obj1 = doc.object();//返回文档内的对象
        if(obj1.contains("result") == false)//问文档对象是否包含result关键字
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("result");//获得关键字result对应的结果
        if(var.isObject() == false)
        {
            qDebug()<<"result的值不是一个对象"<<endl;
            return;
        }
        QJsonObject resultObj = var.toObject();//把result的值转为一个对象
        if(resultObj.contains("songs") == false)
        {
            qDebug()<<"JSON对象没有歌曲"<<endl;
            return;
        }
        var = resultObj.value("songs");//得到关键字songs的值
        if(var.isArray())//是否为数组？
        {
            QJsonArray songsArr = var.toArray();//把songs的值转为一个数组
            qDebug()<<"一共搜索到"<<songsArr.size()<<"首歌曲"<<endl;
            for(int i = 0 ; i < songsArr.size() ; i++)
            {
                QJsonObject songObj = songsArr[i].toObject();//把下标为i的元素转为对象
                if(songObj.contains("id"))
                {
                    QJsonValue varID = songObj.value("id");//获取关键字为id的元素的值
                    id = varID.toDouble();//把值转为整数
                }
                if(songObj.contains("name"))
                {
                    QJsonValue varName = songObj.value("name");
                    songName = varName.toString();
                }
                if(songObj.contains("album"))//是否包含专辑
                {
                    QJsonValue varAlbum = songObj.value("album");//得到专辑关键字的值
                    if(varAlbum.isObject())
                    {
                        QJsonObject albumObj = varAlbum.toObject();//把专辑的值转为对象
                        if(albumObj.contains("name"))
                        {
                            QJsonValue varAlbumName =  albumObj.value("name");
                            albumName = varAlbumName.toString();//得到专辑名
                        }
                    }
                }
                if(songObj.contains("artists"))//是否包含作者关键字
                {
                    QJsonValue varArtists = songObj.value("artists");
                    if(varArtists.isArray())//作者的值是否为数组？
                    {
                       QJsonArray arrArtists = varArtists.toArray();
                       for (int i = 0; i < arrArtists.size(); ++i) {//遍历作者数组
                           if(arrArtists[i].isObject())
                           {
                               QJsonObject artistsObj = arrArtists[i].toObject();
                               if(artistsObj.contains("name"))
                               {
                                   QJsonValue varArtistsName = artistsObj.value("name");
                                   singerName+= varArtistsName.toString();//把名字加入到字符串中
                                   singerName+=" ";//中间留一个空格
                               }
                           }
                       }
                    }
                }
                if(songObj.contains("duration"))
                {
                    QJsonValue varDuration = songObj.value("duration");//获取关键字为duration的元素的值
                    duration = varDuration.toInt()/1000/60.0F;//把值转为整数
                }
                qDebug()<<id<<" "<<songName<<" "<<albumName<<" "<<singerName<<" "<<duration<<endl;
                musicIDList.push_back(id);
                 playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                QStandardItem *item = new QStandardItem(songName);//歌名
                pModel->setItem(i, 0, item);
                item = new QStandardItem(albumName);
                pModel->setItem(i, 1, item);
                item = new QStandardItem(singerName);
                pModel->setItem(i, 2, item);
                item = new QStandardItem(QString("%1").arg(duration));
                pModel->setItem(i, 3, item);
                singerName = "";//清空歌手名
            }
            playlist->setCurrentIndex(0);
        }
    }
}

void MusicPlayer::replyFinished(QNetworkReply* reply)
{
    qDebug()<<"--------\"hello\"--------"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)<<endl;
//    QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
        parseJson(reply->readAll());
    }
}


//void MusicPlayer::positionChangedSlots(qint64 position)
//{
//    qDebug()<<position<<endl;

//   ui->hs_songtime->setValue(position);
//}

void MusicPlayer::on_musicTableView_doubleClicked(const QModelIndex &index)
{
    playlist->setCurrentIndex(index.row());
    player->play();
}
//更新播放的进度条和时间
void MusicPlayer::updateDuration(qint64 value)
{
    // 设置播放进度条的范围为 0 到 播放器的总时长
    ui->hs_songtime->setRange(0, player->duration());
    // 设置播放进度条的当前值为当前播放位置
    ui->hs_songtime->setValue(value);
}

//显示歌词
void MusicPlayer::lyricTextShow(QString str)
{
    ui->tb_songtext->setText(str);
}


void MusicPlayer::on_hs_songtime_valueChanged(int value)
{
    //设置时间
    QTime time(0,value/60000,qRound((value%60000)/1000.0));
    ui->lb_time->setText(time.toString("mm:ss"));
    //拖动时不播放，松开播放
    if(canchange == true)
    {
        player->setPosition(value);
    }
}

void MusicPlayer::on_hs_songtime_sliderPressed()
{

        canchange = true;

}

void MusicPlayer::on_hs_songtime_sliderReleased()
{
    canchange = false;
}
